<?php

namespace Core\Common\Handler;

use Core\Common\Base\ConfigSource;
use Core\Common\Base\Consul;

/**
 * 从consul同步配置到内存
 *
 * @author baiyang@ibantang.com
 */
class ConfigHandler
{
    // 发出停止信号后, 是否直接KILL掉，还是要等待本次处理结束
    const TERM  = true;
    const SLEEP = 1000000;
    private static $config = [
        'WaitTime' => 50 * 1000 * 1000000,//50s
    ];

    private static function printLog($data)
    {
        echo json_encode(array_merge([
            "file" => "configHandler",
            "time" => microtime(true),
        ], $data));
    }

    public static function run($notUsed)
    {
        $sleepTime = 5;
        try {
            $kvInstance = Consul::getInstance()->KV();
            $configPath = 'config/' . CORE_NAME . '/data';
            $option     = new \DCarbone\PHPConsulAPI\QueryOptions(self::$config);
            list($kvPair, $_, $error) = $kvInstance->get($configPath, $option);
            if ($error) {
                self::printLog([
                    "msg"   => "fetch consul msg, error",
                    "error" => $error,
                ]);
                sleep($sleepTime);
                return;
            }

            self::printLog([
                "msg"       => "ok",
                "value_len" => strlen($kvPair->Value),
                "index"     => $kvPair->getModifyIndex(),
                "md5"       => md5($kvPair->Value),
            ]);
            if (empty($kvPair->Value)) {
                sleep($sleepTime);
                return;
            }

            ConfigSource::resetAppConfig($kvPair->Value);
        } catch (\Throwable $e) {
            self::printLog([
                "msg" => $e->getTraceAsString(),
            ]);
        }
        sleep($sleepTime);
    }
}
